<?php

namespace App\Http\Middleware;

use App\Models\Base\Charge;
use App\Models\Base\ServerList;
use App\Service\ServerOnlineService;
use Closure;
use Illuminate\Support\Facades\Log;

class CheckSign
{
    /**对外开放接口验证签名
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $params = $request->all();
        if (empty($params)) {
            return response()->json(httpResponse(101, 'param error'));
        }
        $platform_id = $params['platform_id'];
        $sign = $params['sign'];
        $charge = Charge::where('channel_no', $platform_id)->pluck('app_key');
        if ($charge->isEmpty()) {
            return response()->json(httpResponse(101, 'platformId error'));
        }
        $verify_sign = checkSign($params, $charge->first());
        Log::info('sign_key', ['key' => $verify_sign, 'params' => $params]);
        if (0 !== strcasecmp($sign, $verify_sign)) {
            Log::error('sign_key_error');

            return response()->json(httpResponse(103, 'sign error'));
        }
        if (false == $this->verifyServer($params)) {
            return response()->json(httpResponse(101, 'param error'));
        }

        return $next($request);
    }

    /**
     * [verifyServer 验证游戏服参数].
     *
     * @Author   王文凡
     * @DateTime 2018-05-09
     *
     * @version  1.0
     *
     * @param [type] $params [description]
     *
     * @return [type] [description]
     */
    protected function verifyServer($params)
    {
        if ($server_id = $params['server_id']) {
            $server_id = ServerOnlineService::mergeServerId($server_id);
            $server = ServerList::where('server_id', $server_id)->first();
            if ($server) {
                setDB($server_id);

                return true;
            } else {
                return false;
            }
        }

        return true;
    }
}
